package com.example.a02back.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.a02back.dto.returnMessage;
import com.example.a02back.entity.Message;
import com.example.a02back.mapper.MessageMapper;
import com.example.a02back.service.IMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author SimpChaos
 * @since 2022-07-02
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Resource
    private UserServiceImpl userService;


    /**
     * @Description:
     * @Author: SimpChaos
     * @Date: 2022/7/20 17:35
     * @Param: [token, send, receive, content]
     * @Return: java.lang.String
     */
    public String send(String token,String send,String receive,String content,String roomid){
        Message m =new Message();
        m.setRequestId(token);
        m.setReceiver(receive);
        m.setSender(send);
        m.setContent(content);
        m.setIsRead(0);
        m.setRoomId(roomid);
        return  String.valueOf(this.save(m));
    }



    public List<returnMessage> receive(String send,String receive,String roomid){
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getSender,send).eq(Message::getReceiver,receive).eq(Message::getIsRead,0).eq(Message::getRoomId,roomid);
        List<Message> m = this.list(wrapper);
        returnMessage r = new returnMessage();
        List<returnMessage> s = new ArrayList<>();
        for(Message message:m){
            BeanUtil.copyProperties(message,r);
            r.setAvatarUrl(userService.getById(send).getAvatarUrl());
            message.setIsRead(1);
            this.updateById(message);
            s.add(r);
        }
        return s;
    }

}
